package com.financing.wap.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.financing.wap.service.*;
import com.financing.wap.util.*;
import com.financing.wap.web.controller.api.SendEmailController;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.mail.dto.MailContentDTO;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dao.ICorpDao;
import com.financing.wap.dto.CompanyInvitationCodeDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.UserDTO;

@Service("registerService")
public class RegisterServiceImpl implements IRegisterService{
	/**
	 * 日志类
	 */
	protected static Logger log = LoggerFactory
			.getLogger(RegisterServiceImpl.class);

	@Autowired
	private IUserService userService;

	@Autowired
	private EmailSendServiceImp mailSenderService;

	@Autowired
	private IEmailTemplateService emailTemplateServiceImpl;

	@Autowired
	private IActivitesService activitesService;

	@Autowired
	private ICorpDao corpDao;

	/**
	 * 
	 * 
	 * @Title: doRegister
	 * 
	 * @Description: 注册
	 * 
	 * @param @param register
	 * 
	 * @return UserDTO 返回类型
	 * 
	 * @throws
	 */
	public UserDTO doRegister(RegisterDTO register) {
		log.info("start register");

		UserDTO user = new UserDTO();
		user.setLoginName(register.getMobile());
		user.setMobile(register.getMobile());
		//判断是否有密码
		if(!StringUtils.isBlank(register.getPassword())){
			// 对密码进行加密
			String password = register.getPassword();
			String securePassword = SecureUtil.MD5EncryptAndBase64(password);
			
			user.setPassword(securePassword);
		}
		//未传入状态设置 默认
		if(StringUtils.isBlank(register.getuShoprole())){
			user.setuShoprole("1");
		}else{
			user.setuShoprole(register.getuShoprole());
		}
		
		user.setuFrom(register.getuFrom());
		String sourceCodeInt = "0";
		
		// 加入广告来源注册sourceCode
//		user.setMediaSource(StringUtil.isNullOrEmptyStr((String) SessionUtil
//				.getSession().getAttribute("mid")) ? Constants.MEDIA_SOURCE_PT
//				: (String) SessionUtil.getSession().getAttribute("mid"));
		String mediaSource = register.getMediaSource();
		if(StringUtil.isNullOrEmptyNStr(mediaSource)){
			user.setMediaSource(Constants.MEDIA_SOURCE_PT);
		}else{
			user.setMediaSource(mediaSource);
		}

		// 注册来源手机号 如果为空 sourceCodeInt 取 register.getSourceCode()
		// 注册来源手机号 如果不为空 查询数据库 sourceCodeInt 取 userID 对象为空 ourceCodeInt 取
		// register.getSourceCode()
		
		log.info("in doRegister getSourceMobile :"+register.getSourceMobile());
		if (StringUtil.isNullOrEmptyStr(register.getSourceMobile())) {
			try {
				sourceCodeInt = StringUtil.isNullOrEmptyStr(register
						.getSourceCode()) ? "0" : 
						register.getSourceCode();
				log.info("in doRegister sourceCodeInt :"+sourceCodeInt);
			} catch (Exception e) {
				log.error("in doRegister sourceCodeInt error:",e);
				sourceCodeInt = "0" ;
			}

		} else {
			UserDTO userSource = new UserDTO();
			userSource.setLoginName(register.getSourceMobile());
			
			log.info("in doRegister SourceMobile :"+register.getSourceMobile());
			
			userSource = userService.queryUserByMobile(userSource);
			if (userSource == null) {
				sourceCodeInt = StringUtil.isNullOrEmptyStr(register
						.getSourceCode()) ? "0" : 
						register.getSourceCode();
				
				log.info("in doRegister SourceMobile userSource is null");
				
			} else {
				sourceCodeInt = userSource.getId();
				
				log.info("in doRegister SourceMobile sourceCodeInt:"+sourceCodeInt);
			}
			
		}
		user.setRemark((String) SessionUtil.getSession().getAttribute("wi"));
		user.setSourceCode(sourceCodeInt);

		// 活动来源-从前端传入
		user.setActSource(register.getActSource());
		// 校验数据格式

		// 判断是否为机构下面的账号
		if (!StringUtil.isNullOrEmptyStr(register.getSourceMobile())) {

			CompanyInvitationCodeDTO cic = new CompanyInvitationCodeDTO();
			cic.setCompanyInvitationCode(register.getSourceMobile().trim());
			cic = corpDao.getCorpInvitationCode(cic);
			log.info("in getSourceMobile sugar");
			// 邀请码为机构邀请码
			if (cic != null && cic.getCompanyId() != null) {
				log.info("in getSourceMobile sugar cic!=null&& cic.getCompanyId()!= null");
				user.setManagerId(cic.getCompanyId());
				// 设置fa用户类型为机构fa
				user.setuType("3");
			} else {
				UserDTO u = new UserDTO();
				u.setLoginName(register.getSourceMobile().trim());
				u = userService.queryUserByMobile(u);
				log.info("in getSourceMobile sugar:" + u);

				if (u != null && "1".equals(u.getuType())) {
					user.setManagerId(u.getId());
					// 设置fa用户类型为机构fa
					user.setuType("3");
				} else if (u != null && "3".equals(u.getuType())) {
					user.setManagerId(u.getManagerId());

				}
			}
		}

		// 创建用户   --返回一些 必须字段
		Map<String,String> map = userService.registerUser(user);

		//doActiveForMap(user,map);
		//判断是否活动自动通过
		if(StringUtils.isBlank(user.getRole())){
			user.setRole("1");
		}
		return user;
	}


	/**** 注入 活动- ****/
	public UserDTO doActiveForMap(UserDTO user,Map<String,String> map) {
		try {
		/*	activitesService.operatingActivities(Constants.ACTIVITIES_CODE_ING,
					user);*/
			log.info("mailSenderService registering sendMail begin");
			user = userService.getUserToSendEmail(user);
			// 注册成功后，发送邮件给相关人员进行跟进
			if (null == user.getActSource()
					|| "".equals(user.getActSource().trim())) {
				user.setActSource("无活动来源");
			}
			if (null == user.getRemark()
					|| "".equals(user.getActSource().trim())) {
				user.setRemark("无备注");
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("loginName", user.getLoginName());
			param.put("id", user.getId());
			param.put("mobile", user.getMobile());
			param.put("createDate",
					new SimpleDateFormat("HH:mm;yyyy-MM-dd").format(new Date())
							.replaceAll(";", "&nbsp;&nbsp;&nbsp;&nbsp;"));

			param.put("mediaSource", Constants.sourceCodeMap.get(user.getMediaSource()));
			param.put("actSource", user.getActSource());
			param.put("remark", user.getRemark());
			// 获取拼接后的标题内容
			param = emailTemplateServiceImpl.spliceEmailContent(
					Constants.mail_template_user_register, param);
			// 获取收件人
			String sendToString = PropertiesUtils
					.getValue("register.email.send.to");
			// 获取抄送人
			String sendCopyToString = PropertiesUtils
					.getValue("register.email.send.copy.to");
			// 原jar包
			MailContentDTO mail = new MailContentDTO();
			mail.setRecAddress(sendToString);
			mail.setCc(sendCopyToString);
			mail.setSubject(param.get("subject").toString());
			mail.setContext(param.get("content").toString());
			mailSenderService.send(mail);
			log.info("mailSenderService registering sendMail end");

			log.info("mailSenderService registering sendSMS begin");

			//发送短信
			List<String> mobileList = new ArrayList<String>();

			//如果是销售邀请的-直接通知销售
			if(map != null && StringUtils.isNotBlank(map.get("loginName"))){
				mobileList.add(map.get("loginName"));
			}else {
				//获取配置收信人
				String smsSendToString = PropertiesUtils
						.getValue("register.sms.send.to");
				String[] smsList = smsSendToString.split(";");
				for (String phone : smsList) {
					mobileList.add(phone);
				}
			}
			Map<String,Object> msmParam = new HashMap<String,Object>();
			msmParam.put("loginName",user.getLoginName());
			String msg = (String) MessageUtil.getMessage("messageAndMail","registerNotice", msmParam).get(MessageUtil.KEY_CONTENT);
			log.info("mailSenderService registering sendSMS end");

		} catch (Exception e) {
			log.error("notice SFA by registering successful error", e);
		}
		return user;
	}
}
